<template>
  <div class="tableview-root">
    <div class="filter-wrap">
      <div style="width: 10%;">&nbsp;</div>
      <div class="search" style="width: 33%;">
        <TextSearch style="width: 100%;" placeholder="请输入模板标题" :value="searchVal" @search="onSearchText" />
      </div>
      <div class="search">
        <a class="filter-mode" @click="handleChangeView('grid')" v-if="viewModel==='list'">
          <SvgIcon class="x24" name="zu11729a1"></SvgIcon>
        </a>
        <a class="filter-mode" @click="handleChangeView('list')" v-else>
          <SvgIcon class="x24" name="zu11729"></SvgIcon>
        </a>
      </div>
    </div>
    <div class="list-wrapper">
      <el-table
        v-if="dataList.length>0&&viewModel==='list'"
        ref="multipleListTable"
        class="list-table"
        :data="dataList"
        empty-text="暂无数据"
        row-key="_id"
        header-row-class-name="tableview-header"
        row-class-name="tableview-row"
        cell-class-name="tableview-cell"
        style="width: 100%"
        v-loading="loading"
        @row-click="onRowClick"
      >
        <el-table-column column-key="space" width="10" />
        <el-table-column
          v-for="(field, index) in fieldList"
          :key="index"
          :label="field.title"
          :column-key="field.key"
          :width="field.width"
          :min-width="field.width || field.minWidth"
          class-name="link"
        >
          <template #default="scope">
            <template v-if="field.comp">
              <component
                :is="currentComponent(field.comp)"
                type="table"
                :value="unref(scope.row)"
              />
            </template>
            <template v-else-if="field.key === 'formName'">
              <span class="cell-span" :id="scope.row.idkey?'temp'+scope.row.idkey:''"><img class="xfolder-table mr-step" src="@assets/images/fileform.webp" alt="" />{{ scope.row[field.key] }}</span>
            </template>
            <template v-else>
              <span class="cell-span">{{ scope.row[field.key] }}</span>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="操作" :width="250" class-name="table-options" fixed="right">
          <template #default="scope">
            <ToolBar
              :data="scope.row"
              type="list"
              :tools="getToolConfig(scope.row)"
              :tool-width="60"
              @click="handleClick"
            />
          </template>
        </el-table-column>
      </el-table>

      <div v-if="dataList.length>0&&viewModel==='grid'">
        <div class="new-cardpanel" v-for="(bitm, bidx) in dataListNew" :key="bidx">
          <div class="xcardname" :id="'temp'+bitm.idkey">{{ bitm.idname }}</div>
        
          <div class="tw-filegrid">
            <div class="tw-filegrid-item" 
              v-for="(item, index) in bitm.list" 
              :key="index"
              @click="handleRowClick(item)">
              <div class="tw-filegrid-item-body">
                <div class="tw-filegrid-item-remark" :id="item.idkey?item.idkey:''">
                  <img class="xfolder-table mr-step" src="@assets/images/fileform.webp" alt="" />
                  <span style="color: #333;" :title="item.formName">{{item.formName}}</span>
                </div>
                <div>
                  <template v-if="!item.listConf">
                    <el-skeleton animated >
                      <template #template>
                        <div style="padding: 14px">
                          <el-skeleton-item variant="p" style="width: 100%; height: 12px;" />
                          <el-skeleton-item variant="p" style="width: 70%; height: 12px; margin-top: 10px;" />
                          <div
                            style="
                              display: flex;
                              align-items: center;
                              justify-items: space-between;
                            "
                          >
                            <el-skeleton-item variant="text" style="margin-right: 16px; height: 12px;" />
                            <el-skeleton-item variant="text" style="width: 40%; height: 12px;" />
                          </div>
                          <el-skeleton-item variant="p" style="width: 40%; height: 12px;margin-top: 5px;" />
                        </div>
                      </template>
                    </el-skeleton>
                  </template>
                  <div class="container" v-if="item.listConf">
                    <template v-for="(ritm, ridx) in item.listConf.split(',')">
                      <p class="desc"  :key="ridx" v-if="ridx < 3">
                        <span v-html="ritm"></span>:
                      </p>
                    </template>
                  </div>
                </div>
              </div>
              <!-- <div class="tw-filegrid-item-name" style="font-size: 12px;">{{ item.formName }}</div> -->
              <div class="tw-filegrid-item-options">
                <ToolBar
                  :data="item"
                  limit="1"
                  type="list"
                  :tools="getToolConfig(item)"
                  :tool-width="50"
                  @click="handleClick"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      
    </div>

    <div v-if="dataList.length===0">
      <EmptyIndex :data="!searchVal ? noListDataConfig : noSearchDataConfig" />
    </div>

    <ModifyDialog
      :type="modifyType"
      :visible="showModify"
      :question-info="questionInfo"
      @on-close-codify="onCloseModify"
    />
  </div>
</template>

<script setup>
import { ref, computed, unref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { get, map } from 'lodash-es'

import { ElMessage, ElMessageBox } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
import 'element-plus/theme-chalk/src/message-box.scss'

import moment from 'moment'
// 引入中文
import 'moment/locale/zh-cn'
// 设置中文
moment.locale('zh-cn')

import EmptyIndex from '@/management/components/EmptyIndex.vue'
import { CODE_MAP } from '@/management/api/eco/base'
import { QOP_MAP } from '@/management/utils/constant.ts'
import { del as deleteForm, copy as copyForm } from '@/management/api/dataform'
// import { del as deleteCollect, save as saveCollect } from '@/management/api/dataform-collect'
import ModifyDialog from './ModifyDialog.vue'
import TagModule from './TagModule.vue'
import StateModule from './StateModule.vue'
import ToolBar from './ToolBar.vue'
import TextSearch from './TextSearch.vue'
// import { SurveyPermissions } from '@/management/utils/types/formsTypes'
import SvgIcon from '@common/SvgIcon/index.vue'

import {
  fieldConfig,
  noListDataConfig,
  noSearchDataConfig,
  surveyTypeSelect
} from '@/management/config/formsConfig'

const store = useStore()
const router = useRouter()
const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  data: {
    type: Array,
    default: () => []
  },
  total: {
    type: Number,
    default: 0
  }
})
const emit = defineEmits(['reflush'])
const fields = ['formName', 'creatorName', 'lastModifyTime']

const showModify = ref(false)
const modifyType = ref('')
const questionInfo = ref({})

const viewModel = ref(store.state.viewModel)

const currentPage = ref(1)
const searchVal = computed(() => {
  return store.state.templates.searchVal
})
const selectValueMap = computed(() => {
  return store.state.templates.selectValueMap
})
const buttonValueMap = computed(() => {
  return store.state.templates.buttonValueMap
})
const currentComponent = computed(() => {
  return (componentName) => {
    switch (componentName) {
      case 'TagModule':
        return TagModule
      case 'StateModule':
        return StateModule
      default:
        return null
    }
  }
})

const fieldList = computed(() => {
  return map(fields, (f) => {
    return get(fieldConfig, f, null)
  })
})
const data = computed(() => {
  return props.data
})
const total = computed(() => {
  return props.total
})
const dataList = computed(() => {
  return data.value.map((item) => {
    return {
      ...item
    }
  })
})
const dataListNew = computed(() => {
  let templateList = [];
  let tlist = [];
  (data.value || []).forEach((item, index) => {
    let tmp = {
      _id: item.formId,
      ...item
    }
    if (index === 0) {
      tmp.idkey = item.busineType
      tmp.idname = surveyTypeSelect.value.find((itm) => itm.value === item.busineType)?.label

      tlist.push(tmp)
    } else if (data.value[index - 1].busineType !== item.busineType) {
      templateList.push({
        idkey: tlist[0].idkey,
        idname: tlist[0].idname,
        list: [...tlist]
      })
      tlist = []

      tmp.idkey = item.busineType
      tmp.idname = surveyTypeSelect.value.find((itm) => itm.value === item.busineType)?.label
      tlist.push(tmp)
    } else {
      tmp.idkey = item.busineType
      tmp.idname = surveyTypeSelect.value.find((itm) => itm.value === item.busineType)?.label

      tlist.push(tmp)
    }

    if (index > 0 && index === data.value.length - 1) {
      templateList.push({
        idkey: tlist[0].idkey,
        idname: tlist[0].idname,
        list: [...tlist]
      })
    }
  })

  return templateList
})
const filter = computed(() => {
  return [
    {
      comparator: '',
      condition: [
        {
          field: 'title',
          value: searchVal.value,
          comparator: '$regex'
        }
      ]
    },
    {
      comparator: '',
      condition: [
        {
          field: 'status',
          value: selectValueMap.value['status']
        }
      ]
    },
    {
      comparator: '',
      condition: [
        {
          field: 'BusineType',
          value: selectValueMap.value.BusineType
        }
      ]
    }
  ]
})
const order = computed(() => {
  const formatOrder = Object.entries(buttonValueMap.value)
    .filter(([, effectValue]) => effectValue)
    .reduce((prev, item) => {
      const [effectKey, effectValue] = item
      prev.push({ field: effectKey, value: effectValue })
      return prev
    }, [])
  return JSON.stringify(formatOrder)
})
const workSpaceId = computed(() => {
  return store.state.templates.workSpaceId
})

const handleChangeView = (viewmodel) => {
  store.commit('setViewModel', viewmodel)
  viewModel.value = viewmodel
}

const onReflush = async () => {
  const filterString = JSON.stringify(
    filter.value.filter((item) => {
      return item.condition[0].value
    })
  )
  let params = {
    curPage: currentPage.value,
    filter: filterString,
    order: order.value
  }
  if (workSpaceId.value) {
    params.workspaceId = workSpaceId.value
  }
  emit('reflush', params)
}

const getToolConfig = () => {
  let funcList = []
  const permissionsBtn = [
    {
      key: QOP_MAP.EDIT,
      label: '编辑'
    },
    {
      key: 'delete',
      label: '删除',
      icon: 'icon-shanchu'
    },
    {
      key: QOP_MAP.COPY,
      label: '复制',
      icon: 'icon-shanchu'
    }
  ]

  funcList = permissionsBtn
  
  const order = ['edit', 'copy', 'delete']
  const result = funcList.sort((a, b) => order.indexOf(a.key) - order.indexOf(b.key))

  return result
}
const handleClick = (key, data) => {
  switch (key) {
    case QOP_MAP.EDIT:
      onModify(data, QOP_MAP.EDIT)
      return
    case QOP_MAP.COPY:
      onCopy(data, QOP_MAP.COPY)
      return
    case 'delete':
      onDelete(data)
      return
    default:
      return
  }
}
const onDelete = async (row) => {
  try {
    await ElMessageBox.confirm('是否确认删除？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch (error) {
    return
  }

  let res
    res = await deleteForm(row)
  
  if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
    ElMessage.success('删除成功')
    store.commit('templates/setFormsTotal', 0)
    store.commit('templates/setFormsHasMore', true)
    currentPage.value = 1
    onReflush()
  } else {
    ElMessage.error(res?.serverResult?.resultMessage || '删除失败')
  }
}

const onModify = (data, type = QOP_MAP.EDIT) => {
  router.push({
    name: 'FormsEditIndex',
    params: {
      id: data._id
    }
  })
}
const onCopy = async (data, type = QOP_MAP.EDIT) => {
  // try {
    const res = await copyForm({
      formId: data._id,
      formType: data.formType
    })

    if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
      const { formId } = res.result
      router.push({
        name: 'FormsEditIndex',
        params: {
          id: formId
        }
      })
    } else {
      ElMessage.error(res?.serverResult?.resultMessage)
    }
  // } catch (err) {
  //   ElMessage.error(err)
  // }
}
const onCloseModify = (type) => {
  showModify.value = false
  questionInfo.value = {}
  if (type === 'update') {
    store.commit('templates/setFormsTotal', 0)
    store.commit('templates/setFormsHasMore', true)
    currentPage.value = 1
    onReflush()
  }
}

const onRowClick = (row) => {
  router.push({
    name: 'FormsEditIndex',
    params: {
      id: row._id
    }
  })
}
const handleRowClick = (row) => {
  router.push({
    name: 'FormsEditIndex',
    params: {
      id: row._id
    }
  })
}
const onSearchText = (e) => {
  store.commit('templates/setSearchVal', e)
  currentPage.value = 1
  onReflush()
}

</script>

<style lang="scss" scoped>
.tableview-root {
  .filter-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .select {
      display: flex;
    }
    .search {
      display: flex;
    }

    .filter-mode {
      padding: 6px 0;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .list-wrapper {
    
    background: #fff;
    .list-table {
      min-height: 620px;
    }
  }

  .list-pagination {
    margin-top: 20px;
    :deep(.el-pagination) {
      display: flex;
      justify-content: flex-end;
    }
  }
  :deep(.el-table__header) {
    .tableview-header .el-table__cell {
      .cell {
        height: 24px;
        color: #4a4c5b;
        font-size: 14px;
      }
    }
  }
  :deep(.tableview-row) {
    .tableview-cell {
      padding: 5px 0;
      &.link {
        cursor: pointer;
      }
      .cell .cell-span {
        font-size: 14px;
      }
    }
  }

  .new-cardpanel {
    background: #FBFBFB;
    border-radius: 12px;
    padding: 10px 15px 0 15px;
    margin-bottom: 20px;

    .xcardname {
      font-size: 14px;
      color: #333;
      margin-bottom: 15px;
    }
  }
}
.el-select-dropdown__wrap {
  background: #eee;
}
.el-select-dropdown__item.hover {
  background: #fff;
}

.tw-filegrid {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.tw-filegrid-item {
  width: calc(16.67% - 9px);
  margin-right: 10px;
  margin-bottom: 20px;
  background: #FFFFFF;
  position: relative;

  .container {
      display: flex;
      flex-direction: column;
      margin-top: 15px;
      padding: 10px;
      height: 75px;
      background: #FFFFFF;
      border-radius: 4px 4px 4px 4px;
      // border: 1px solid #E8E8E8;
      overflow: hidden;
      color: #999;
      font-size: 12px;
      line-height: 22px;
      .desc {
        width: 100%;
        height: 28px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        position: relative;
        padding-left: 12px;
      }
      .desc::before {
        left: 0px;
        top: 8px;
        content: ' ';
        display: inline-block;
        width: 4px;
        height: 4px;
        background: #e6e8eb;
        border-radius: 50%;
        position: absolute;
      }
    }
}

.tw-filegrid-item:nth-child(6n) {
  margin-right: 0px;
}
.tw-filegrid-item-options {
  position: absolute;
  right: 0;
  top: 0;
  visibility: hidden;
}
.tw-filegrid-item:hover .tw-filegrid-item-options {
  visibility: visible;
}
.tw-filegrid-item-body {
  box-shadow: 0px 6px 16px 1px rgba(0,0,0,0.06);
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #ECECEC;
  padding: 10px 10px 5px 10px;
  height: 146px;
}
.tw-filegrid-item-name {
  margin-top: 10px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.tw-filegrid-item-remark {
  margin-top: 5px;
  color: #999;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
  > span {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

@media (max-width: 1699px) {
  .tw-filegrid-item {
    width: calc(16.67% - 9px);
  }

  .tw-filegrid-item:nth-child(6n) {
    margin-right: 0px;
  }
}

// @media (max-width: 1599px) {
//   .tw-filegrid-item {
//     width: calc(14.3% - 9px);
//   }

//   .tw-filegrid-item:nth-child(8n) {
//     margin-right: 10px;
//   }
//   .tw-filegrid-item:nth-child(7n) {
//     margin-right: 0px;
//   }
// }

@media (max-width: 1499px) {
  .tw-filegrid-item {
    width: calc(25% - 8px);
  }

  .tw-filegrid-item:nth-child(6n) {
    margin-right: 10px;
  }
  .tw-filegrid-item:nth-child(4n) {
    margin-right: 0px;
  }
}

// @media (max-width: 1299px) {
//   .tw-filegrid-item {
//     width: calc(25% - 8px);
//   }

//   .tw-filegrid-item:nth-child(5n) {
//     margin-right: 10px;
//   }
//   .tw-filegrid-item:nth-child(4n) {
//     margin-right: 0px;
//   }
// }

</style>
